from typing import Optional, List

from fastapi import Depends, Body, Query, Header, Request
from fastapi_utils.cbv import cbv
from fastapi_utils.inferring_router import InferringRouter
from sqlalchemy.orm import Session

from server.app.cloud_ide.schema.ide_environment.request.ide_environment_create_request import \
    IdeEnvironmentCreateRequest
from server.app.cloud_ide.schema.ide_environment.request.ide_environment_update_request import \
    IdeEnvironmentUpdateRequest
from server.app.cloud_ide.service.ide_environment_service import IdeEnvironmentService
from server.framework.core.http_schemas import CommonResponseSchema, TableResponseSchema
from server.framework.core.injects import get_db
from server.framework.core.schemas import OptionsSchema
from server.framework.utils.kubernetes.kubernetes_client import KubernetesClient

ide_environment_api = InferringRouter()


@cbv(ide_environment_api)
class IdeEnvironmentApi:
    ide_environment_service = IdeEnvironmentService()
    db: Session = Depends(get_db)

    @ide_environment_api.get("/get_entity", name='获取环境配置实体')
    async def get_entity(self, id: str = Query(None, description='环境配置id')):
        entity = self.ide_environment_service.get_ide_environment_by_id(self.db, id)
        return entity

    @ide_environment_api.get("/get_ide_environment_options", name='获取环境配置下拉选项')
    async def get_ide_environment_options(self,
                                          group: Optional[str] = Header(None)) -> List[OptionsSchema]:
        query = self.ide_environment_service.get_all_environments(self.db, group)

        option_results: List[OptionsSchema] = []
        for row in query:
            option_results.append(OptionsSchema(value=str(row.id), label=row.name))
        return option_results

    @ide_environment_api.get("/list", response_model=TableResponseSchema, name='获取环境配置列表')
    async def list(self, request: Request,
                   name: Optional[str] = Query(None, description='过滤条件:环境配置名称'),
                   group: Optional[str] = Header(None),
                   current: Optional[int] = Query(1, description='当前页数'),
                   page_size: Optional[int] = Query(10, description='每页记录的数量',
                                                    alias='pageSize')) -> TableResponseSchema:
        """
        获取环境配置列表
        :return:
        """
        if request.state.is_admin:
            items, total = self.ide_environment_service.get_ide_environment_list(self.db, name, group, page_size,
                                                                                 current,
                                                                                 filter_by_tenent=False)
        else:
            items, total = self.ide_environment_service.get_ide_environment_list(self.db, name, group, page_size,
                                                                                 current,
                                                                                 filter_by_tenent=True)
        return TableResponseSchema(data=items, total=total, page=page_size, success=True)

    @ide_environment_api.post("/create", response_model=CommonResponseSchema, name='创建环境配置')
    async def create(self, data: IdeEnvironmentCreateRequest = Body(None, description='环境配置创建实体'),
                     group: Optional[str] = Header(None),
                     db: Session = Depends(get_db)) -> CommonResponseSchema:
        """
        创建开发环境配置
        :return:
        """
        data.tenant_id = group
        rs = self.ide_environment_service.create_ide_environment(db, data)
        if rs:
            return CommonResponseSchema(data={}, message=f'创建成功', success=True)
        else:
            return CommonResponseSchema(data={}, message=f'创建失败', success=False)

    @ide_environment_api.get("/get_storage_class_options", name='获取存储卷')
    async def get_storage_class_options(self) -> List[OptionsSchema]:
        kubernetes_client = KubernetesClient()
        storage_classes = kubernetes_client.list_storage_classes()
        option_results: List[OptionsSchema] = []
        for row in storage_classes:
            option_results.append(OptionsSchema(value=str(row.name), label=row.name))
        return option_results

    @ide_environment_api.get("/delete", response_model=CommonResponseSchema, name='删除环境配置')
    async def delete(self, ids: str = Query(None, description='环境配置id，多条记录以逗号分割')) -> CommonResponseSchema:
        """
        删除开发环境配置
        :return:
        """
        rs = self.ide_environment_service.delete_ide_environment(self.db, ids.split(','))
        if rs:
            return CommonResponseSchema(data={}, message=f'删除成功', success=True)
        else:
            return CommonResponseSchema(data={}, message=f'删除失败', success=False)

    @ide_environment_api.post("/edit", response_model=CommonResponseSchema, name='编辑环境配置')
    async def edit(self, data: IdeEnvironmentUpdateRequest = Body(None, description='环境配置编辑实体'),
                   group: Optional[str] = Header(None)) -> CommonResponseSchema:
        """
        编辑开发环境配置
        :return:
        """
        data.tenant_id = group
        rs = self.ide_environment_service.update_ide_environment(self.db, data)
        if rs:
            return CommonResponseSchema(data={}, message=f'编辑成功', success=True)
        else:
            return CommonResponseSchema(data={}, message=f'编辑失败', success=False)
